package com.exit66.jukebox.servlet.xml;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.StringTokenizer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.exit66.jukebox.util.XmlSegment;

public abstract class XmlResponseServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse res)
	throws ServletException, IOException 
	{
		doPost(req, res);
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse res)
	throws ServletException, IOException 
	{
		XmlSegment xml = new XmlSegment();
		xml.appendString("<?xml version=\"1.0\"?>\n<response>");
		
		buildXml(req, xml);
		
		xml.appendString("</response>");
		PrintWriter out = res.getWriter();
		out.print(xml.getOutput());
		out.close();
	}
	
	abstract protected void buildXml(HttpServletRequest req, XmlSegment xml);
	
    protected String[] splitString(String input, String sep) {
        
        StringTokenizer st = new StringTokenizer(input, sep);
        String[] t = new String[st.countTokens()];
        while (st.hasMoreTokens()) t[t.length-st.countTokens()] = st.nextToken();
        
        return t;
        
    }
}
